from PySide6.QtWidgets import (QDialog, QVBoxLayout, QHBoxLayout, QFormLayout,
                              QLabel, QComboBox, QSpinBox, QPushButton, QGroupBox,
                              QLineEdit, QCheckBox, QButtonGroup, QRadioButton)
from PySide6.QtCore import Qt, Signal
from PySide6.QtGui import QKeySequence, QKeyEvent, QMouseEvent

class HotkeyEdit(QLineEdit):
    """统一的快捷键输入框，支持鼠标+键盘组合"""

    def __init__(self, parent=None):
        super().__init__(parent)
        self.setReadOnly(True)
        self.setPlaceholderText("点击此处设置快捷键...")
        self.hotkey_data = {
            "ctrl": False,
            "shift": False,
            "alt": False,
            "key": "",
            "mouse_button": ""
        }
        self.setMinimumHeight(30)

    def mousePressEvent(self, event):
        """捕获鼠标按键事件 - 禁用鼠标按键作为触发键"""
        # 鼠标按键暂不支持作为触发键，只处理焦点
        self.setFocus()
        super().mousePressEvent(event)

    def keyPressEvent(self, event):
        """捕获键盘按键事件"""
        key = event.key()
        modifiers = event.modifiers()

        # 忽略修饰键单独按下
        if key in (Qt.Key_Control, Qt.Key_Shift, Qt.Key_Alt, Qt.Key_Meta):
            return

        # 更新修饰键状态
        self.hotkey_data["ctrl"] = bool(modifiers & Qt.ControlModifier)
        self.hotkey_data["shift"] = bool(modifiers & Qt.ShiftModifier)
        self.hotkey_data["alt"] = bool(modifiers & Qt.AltModifier)

        # 获取按键名称
        key_name = QKeySequence(key).toString()
        if key_name:
            self.hotkey_data["key"] = key_name
            self.hotkey_data["mouse_button"] = ""  # 清除鼠标按键

        self.update_display()

    def update_display(self):
        """更新显示文本"""
        parts = []

        # 添加修饰键
        if self.hotkey_data["ctrl"]:
            parts.append("Ctrl")
        if self.hotkey_data["shift"]:
            parts.append("Shift")
        if self.hotkey_data["alt"]:
            parts.append("Alt")

        # 添加主键
        if self.hotkey_data["mouse_button"]:
            mouse_names = {"left": "鼠标左键", "right": "鼠标右键", "middle": "鼠标中键"}
            parts.append(mouse_names.get(self.hotkey_data["mouse_button"], "鼠标"))
        elif self.hotkey_data["key"]:
            parts.append(self.hotkey_data["key"])

        display_text = " + ".join(parts) if parts else ""
        self.setText(display_text)

    def get_hotkey_data(self):
        """获取快捷键数据"""
        return self.hotkey_data.copy()

    def set_hotkey_data(self, data):
        """设置快捷键数据"""
        self.hotkey_data = data.copy()
        self.update_display()

    def clear_hotkey(self):
        """清除快捷键"""
        self.hotkey_data = {
            "ctrl": False,
            "shift": False,
            "alt": False,
            "key": "",
            "mouse_button": ""
        }
        self.setText("")

class TriggerSettingsDialog(QDialog):
    """触发器设置对话框"""
    def __init__(self, trigger_item, parent=None):
        super().__init__(parent)
        self.trigger_item = trigger_item
        self.setWindowTitle("触发器设置")
        self.setModal(True)
        self.resize(500, 450)
        self.setup_ui()
        self.load_settings()

    def setup_ui(self):
        """设置UI"""
        layout = QVBoxLayout(self)

        # 触发模式设置
        mode_group = QGroupBox("触发模式")
        mode_layout = QFormLayout(mode_group)

        self.mode_combo = QComboBox()
        self.mode_combo.addItems(["按下", "释放", "点击"])
        mode_layout.addRow("模式:", self.mode_combo)

        layout.addWidget(mode_group)

        # 快捷键设置
        hotkey_group = QGroupBox("快捷键设置")
        hotkey_layout = QVBoxLayout(hotkey_group)

        # 说明文本
        info_label = QLabel("工作原理：检测到目标颜色 + 用户按下触发键 → 自动执行鼠标左键点击\n\n✨ 持续触发功能：\n• 按住触发键：持续执行鼠标左键点击\n• 释放触发键：停止执行\n• 触发间隔：控制点击频率\n\n支持的触发键：\n• 键盘按键：如 A, Space, Enter, F1 等\n• 修饰键组合：如 Ctrl+C, Alt+Tab, Shift+F1\n• 注意：鼠标按键暂不支持作为触发键")
        info_label.setStyleSheet("color: #666; font-size: 11px; margin: 5px; background-color: #f0f0f0; padding: 8px; border-radius: 4px;")
        info_label.setWordWrap(True)
        hotkey_layout.addWidget(info_label)

        # 快捷键输入区域
        input_layout = QHBoxLayout()
        input_layout.addWidget(QLabel("快捷键:"))

        self.hotkey_edit = HotkeyEdit()
        input_layout.addWidget(self.hotkey_edit)

        # 清除按钮
        self.clear_btn = QPushButton("清除")
        self.clear_btn.setFixedWidth(60)
        self.clear_btn.clicked.connect(self.hotkey_edit.clear_hotkey)
        input_layout.addWidget(self.clear_btn)

        hotkey_layout.addLayout(input_layout)

        # 预设快捷键
        preset_layout = QHBoxLayout()
        preset_layout.addWidget(QLabel("常用预设:"))

        preset_buttons = [
            ("空格", {"key": "Space"}),
            ("回车", {"key": "Return"}),
            ("F1", {"key": "F1"}),
            ("Ctrl+C", {"ctrl": True, "key": "C"}),
            ("Ctrl+V", {"ctrl": True, "key": "V"}),
            ("Alt+Tab", {"alt": True, "key": "Tab"})
        ]

        for text, data in preset_buttons:
            btn = QPushButton(text)
            btn.setFixedHeight(25)
            btn.clicked.connect(lambda checked, d=data: self.set_preset_hotkey(d))
            preset_layout.addWidget(btn)

        preset_layout.addStretch()
        hotkey_layout.addLayout(preset_layout)

        layout.addWidget(hotkey_group)

        # 触发次数设置
        count_group = QGroupBox("触发次数")
        count_layout = QFormLayout(count_group)

        self.count_spin = QSpinBox()
        self.count_spin.setRange(0, 9999)
        self.count_spin.setSpecialValueText("无限")
        count_layout.addRow("次数:", self.count_spin)

        layout.addWidget(count_group)

        # 触发间隔设置
        interval_group = QGroupBox("触发间隔")
        interval_layout = QFormLayout(interval_group)

        self.interval_spin = QSpinBox()
        self.interval_spin.setRange(10, 10000)
        self.interval_spin.setSuffix(" 毫秒")
        interval_layout.addRow("间隔:", self.interval_spin)

        layout.addWidget(interval_group)

        # 按钮区域
        button_layout = QHBoxLayout()
        button_layout.addStretch()

        self.ok_btn = QPushButton("确定")
        self.ok_btn.clicked.connect(self.accept)
        button_layout.addWidget(self.ok_btn)

        self.cancel_btn = QPushButton("取消")
        self.cancel_btn.clicked.connect(self.reject)
        button_layout.addWidget(self.cancel_btn)

        layout.addLayout(button_layout)

    def set_preset_hotkey(self, data):
        """设置预设快捷键"""
        # 创建完整的快捷键数据
        hotkey_data = {
            "ctrl": data.get("ctrl", False),
            "shift": data.get("shift", False),
            "alt": data.get("alt", False),
            "key": data.get("key", ""),
            "mouse_button": data.get("mouse_button", "")
        }
        self.hotkey_edit.set_hotkey_data(hotkey_data)

    def load_settings(self):
        """加载当前设置"""
        # 加载触发模式
        mode_map = {"press": 0, "release": 1, "click": 2}
        self.mode_combo.setCurrentIndex(mode_map.get(self.trigger_item.trigger_mode, 0))

        # 加载快捷键设置
        self.load_hotkey_from_trigger_item()

        # 加载触发次数和间隔
        self.count_spin.setValue(self.trigger_item.trigger_count)
        self.interval_spin.setValue(self.trigger_item.trigger_interval)

    def load_hotkey_from_trigger_item(self):
        """从触发器项目加载快捷键设置"""
        trigger_key = self.trigger_item.trigger_key

        # 解析现有的快捷键格式
        hotkey_data = {
            "ctrl": False,
            "shift": False,
            "alt": False,
            "key": "",
            "mouse_button": ""
        }

        if trigger_key in ["left", "right", "middle"]:
            # 简单的鼠标按键
            hotkey_data["mouse_button"] = trigger_key
        elif "+" in trigger_key:
            # 组合键
            parts = trigger_key.split("+")
            for part in parts:
                part = part.strip()
                if part.lower() == "ctrl":
                    hotkey_data["ctrl"] = True
                elif part.lower() == "shift":
                    hotkey_data["shift"] = True
                elif part.lower() == "alt":
                    hotkey_data["alt"] = True
                else:
                    # 检查是否是鼠标按键
                    if part.lower() in ["left", "right", "middle"]:
                        hotkey_data["mouse_button"] = part.lower()
                    else:
                        hotkey_data["key"] = part
        else:
            # 单个键盘按键
            hotkey_data["key"] = trigger_key

        self.hotkey_edit.set_hotkey_data(hotkey_data)

    def get_settings(self):
        """获取设置结果"""
        # 获取触发模式
        mode_map = {0: "press", 1: "release", 2: "click"}
        trigger_mode = mode_map[self.mode_combo.currentIndex()]

        # 获取快捷键设置
        trigger_key = self.build_trigger_key_string()

        return {
            "trigger_mode": trigger_mode,
            "trigger_key": trigger_key,
            "trigger_count": self.count_spin.value(),
            "trigger_interval": self.interval_spin.value()
        }

    def build_trigger_key_string(self):
        """构建触发按键字符串"""
        hotkey_data = self.hotkey_edit.get_hotkey_data()

        # 如果没有设置任何按键，返回默认值（空格键）
        if not hotkey_data["key"] and not hotkey_data["mouse_button"]:
            return "Space"

        parts = []

        # 添加修饰键
        if hotkey_data["ctrl"]:
            parts.append("Ctrl")
        if hotkey_data["shift"]:
            parts.append("Shift")
        if hotkey_data["alt"]:
            parts.append("Alt")

        # 添加主键（只处理键盘按键，忽略鼠标按键）
        if hotkey_data["key"]:
            parts.append(hotkey_data["key"])

        return "+".join(parts) if parts else "Space"
